package com.xh.bussiness.thirdapi.xiaobao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xh.bussiness.log.model.AsynThirdLog;
import com.xh.bussiness.log.service.IAsynThirdLogService;
import com.xh.bussiness.permission.bean.request.UserRequest;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.bean.dto.StudentBean;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.thirdapi.xiaobao.config.XbConfig;
import com.xh.bussiness.thirdapi.xiaobao.constant.XbApiConstant;
import com.xh.bussiness.thirdapi.xiaobao.dto.VO.XbResultVO;
import com.xh.bussiness.thirdapi.xiaobao.model.XbClass;
import com.xh.bussiness.thirdapi.xiaobao.model.XbEmployee;
import com.xh.bussiness.thirdapi.xiaobao.model.XbStudent;
import com.xh.bussiness.thirdapi.xiaobao.service.IXiaobaoService;
import com.xh.bussiness.thirdapi.xiaobao.sha256.Sha256Util;
import com.xh.bussiness.tms.model.Class;
import com.xh.bussiness.tms.service.IClassManageService;
import com.xh.core.exception.XhException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author Pitt Cheung
 * @date 2021/6/23 16:03
 */
@Service
public class XiaobaoServiceImpl implements IXiaobaoService {

    @Autowired
    private XbConfig xbConfig;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IAsynThirdLogService asynThirdLogService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IClassManageService classManageService;

    @Override
    public int importTeacher() {
        Map<String, Object> params = new HashMap<>();
        params.put("pageSize", 50);

        int pageNo = 0;
        boolean hasMore = true;
        int totalRecord = 0;
        do {
            pageNo++;
            params.put("pageIndex", pageNo);
            XbResultVO<List<Map<String, Object>>> xbResultVO = sendPostRequest(XbApiConstant.GET_EMPLOYEE, params);
            List<Map<String, Object>> datas = xbResultVO.getData();
            if (CollectionUtils.isEmpty(datas)) {
                hasMore = false;
            }else{
                syncUser(datas);
                totalRecord += datas.size();
            }
        } while (hasMore);

        AsynThirdLog log = new AsynThirdLog();
        log.setImportName("校宝教师导入");
        log.setImportTotal(totalRecord);
        asynThirdLogService.insert(log);

        return totalRecord;
    }

    @Override
    public int importStudent(String beginDate,String  endDate) {
        Map<String, Object> params = new HashMap<>();
        params.put("beginDate", beginDate);
        params.put("endDate", endDate);
        params.put("pageSize", 50);

        int pageNo = 0;
        boolean hasMore = true;
        int totalRecord = 0;
        do {
            pageNo++;
            params.put("pageIndex", pageNo);
            XbResultVO<List<Map<String, Object>>> xbResultVO = sendPostRequest(XbApiConstant.GET_STUDENT, params);
            List<Map<String, Object>> datas = xbResultVO.getData();
            if (CollectionUtils.isEmpty(datas)) {
                hasMore = false;
            }else{
                syncStudent(datas);
                totalRecord += datas.size();
            }
        } while (hasMore);

        AsynThirdLog log = new AsynThirdLog();
        log.setImportName("校宝学生导入");
        log.setImportTotal(totalRecord);
        asynThirdLogService.insert(log);

        return totalRecord;
    }

    @Override
    public int importClass(String beginDate, String endDate) {
        Map<String, Object> params = new HashMap<>();
        params.put("beginDate", beginDate);
        params.put("endDate", endDate);
        params.put("pageSize", 50);

        int pageNo = 0;
        boolean hasMore = true;
        int totalRecord = 0;
        do {
            pageNo++;
            params.put("pageIndex", pageNo);
            XbResultVO<List<Map<String, Object>>> xbResultVO = sendPostRequest(XbApiConstant.GET_CLASS, params);
            List<Map<String, Object>> datas = xbResultVO.getData();
            if (CollectionUtils.isEmpty(datas)) {
                hasMore = false;
            }else{
                syncClass(datas);
                totalRecord += datas.size();
            }
        } while (hasMore);

        AsynThirdLog log = new AsynThirdLog();
        log.setImportName("校宝班级导入");
        log.setImportTotal(totalRecord);
        asynThirdLogService.insert(log);

        return totalRecord;
    }


    private void syncUser(List<Map<String, Object>> xbEmployees) {
        for (Map<String, Object> data : xbEmployees) {
            XbEmployee xbEmployee = BeanUtil.mapToBean(data, XbEmployee.class, false, null);
            User exists = userService.queryUserByThirdId(xbEmployee.getHrDocId().toString(), 2);
            if (exists != null) {
                User user = new User();
                user.setId(exists.getId());
                user.setStatus(0);
                user.setUsername(xbEmployee.getName());
                user.setMobile(xbEmployee.getMobile());
                userService.update(user);
            }else{
                UserRequest request = UserRequest.builder()
                        .mobile(xbEmployee.getMobile())
                        .nickname(xbEmployee.getName())
                        .username(xbEmployee.getName())
                        .status(0)
                        .isFront(1)
                        .isAdmin(1)
                        .source(2)
                        .thirdId(xbEmployee.getHrDocId().toString())
                        .roleIds(Collections.singletonList("2")).build();
                userService.addUser(request);
            }
        }
    }

    private void syncStudent(List<Map<String, Object>> xbStudents) {
        for (Map<String, Object> data : xbStudents) {
            XbStudent xbStudent = BeanUtil.mapToBean(data, XbStudent.class, false, null);
            StudentBean student = new StudentBean();
            student.setId(xbStudent.getStuId().toString());
            student.setName(xbStudent.getStuName());
            // 获取学生的登录手机号：1、学生自己的手机号  2、母亲的手机号  3、父亲的手机号
            String phone = StringUtils.isEmpty(xbStudent.getMainTel()) ? StringUtils.isEmpty(xbStudent.getMinorTel()) ? StringUtils.isEmpty(xbStudent.getOtherTel()) ? null : xbStudent.getOtherTel() : xbStudent.getMinorTel() : xbStudent.getMainTel();
            student.setMotherPhone(phone == null ? null : phone.length() > 11 ? null : phone);
            student.setFatherPhone(xbStudent.getMinorTel());
            student.setSource(2);
            student.setThirdId(xbStudent.getStuId().toString());
            student.setStatus(1);
            studentService.saveOrUpadte(student);
        }
    }

    private void syncClass(List<Map<String, Object>> xbClasses) {
        for (Map<String, Object> data : xbClasses) {
            XbClass xbClass = BeanUtil.mapToBean(data, XbClass.class, false, null);
            //班级状态：0=未开班，1=开班中，2=已结班
            if (xbClass.getStatus().equals(2)) {
                continue;
            }
            Class cls = new Class();
            cls.setId(xbClass.getClassId().toString());
            cls.setTitle(xbClass.getClassName());
            cls.setStatus(1);
            List<Map<String, Object>> teacherList = xbClass.getTeacherList();
            if (!CollectionUtils.isEmpty(teacherList)) {
                Map<String, Object> teacherMap = teacherList.get(0);
                cls.setTeacherId(teacherMap.get("teacherId").toString());
                cls.setTeacherName(teacherMap.get("teacherName").toString());
            }
            cls.setThirdId(xbClass.getClassId().toString());
            cls.setSource("2");
            classManageService.saveOrUpdate(cls);
        }
    }

    private String getToken() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpMethod method = HttpMethod.POST;

        Map<String, String> params = new HashMap<>();
        params.put("accessKeyId", xbConfig.getAccessKeyId());
        params.put("accessKeySecret", xbConfig.getAccessKeySecret());

        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        try {
            ResponseEntity<String> response = restTemplate.exchange(xbConfig.getHost() + XbApiConstant.GET_TOKEN, method, requestEntity, String.class);
            String body = response.getBody();
            if (body != null) {
                return body;
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    private XbResultVO sendPostRequest(String url, Map<String, Object> params) {
        String token = getToken();
        if (StringUtils.isEmpty(token)) {
            throw new XhException("请求发生错误:token is null");
        }
        String timestamp = String.valueOf(System.currentTimeMillis());

        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);
        headers.add("corp-id", xbConfig.getCorpId());
        headers.add("xb-timestamp", timestamp);
        headers.add("xb-sign-method", "sha256");

        String sign = String.format("%s%s%s%s%s%s%s",
                "sha256",
                "POST",
                xbConfig.getAccessKeyId(),
                timestamp,
                url.replace("/", ""),
                JSONObject.toJSONString(params),
                xbConfig.getAccessKeySecret());
        headers.add("xb-sign", Sha256Util.getSHA256StrJava(sign));
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpMethod method = HttpMethod.POST;
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        try {
            ResponseEntity<XbResultVO> response = restTemplate.exchange(xbConfig.getHost() + url, method, requestEntity, XbResultVO.class);
            XbResultVO body = response.getBody();
            if (body != null) {
                return body;
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return null;
    }


}
